import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
const Apps = () => import('@/views/AppsView.vue')
const Login = () => import('@/views/LoginView.vue')
const TestLogin = () => import('@/views/TestLogin.vue')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/test-login',
      name: 'test-login',
      component: TestLogin,
      meta: { requiresAuth: false }
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { requiresAuth: false } // 登录页不需要认证
    },
    {
      path: '/apps',
      name: 'apps',
      component: Apps,
      meta: { requiresAuth: false } // 暂时设为不需要认证，如需要保护改为 true
    },
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: false }
    },
  ],
})

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLoggedIn = !!token
  
  // 如果路由需要认证且用户未登录
  if (to.meta.requiresAuth && !isLoggedIn) {
    // 跳转到登录页，并保存原目标路径
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (to.path === '/login' && isLoggedIn) {
    // 如果已登录且访问登录页，跳转到首页
    next('/apps')
  } else {
    next()
  }
})

export default router
